import module namespace security="http://sendmeafilter.com/common/security" at "common/security.xqy"; 

let $requestMethod := xdmp:get-request-method()
let $url := xdmp:get-request-url()
let $url := 
	if(fn:starts-with($url,'/backoffice')) then
		if(security:allowed("_smaf_backoffice")) then $url else "/somethingthatdoesntexist.xqy"
	else $url
return 
	if($url = '/backoffice' or $url = '/backoffice/') then
		"/backoffice/index.xqy"
	else if($url= "/" or fn:starts-with($url,'/?')) then
		"home.xqy"
	else if(fn:starts-with($url, "/assets")) then
			$url
	else 
		let $url := fn:tokenize($url,'\?')[1]
		let $url :=
			if(fn:ends-with($url,'/')) then 
				fn:substring($url,1,fn:string-length($url) - 1) 
			else $url
		let $url := fn:concat($url,'.xqy')
		let $url := 
			if ($requestMethod eq "GET") then 
					(: Duplicate parameters for the request :) 
					let $names := xdmp:get-request-field-names()
					let $params :=
						if(fn:count($names) > 0) then
							fn:string-join((
								for $name in $names
								for $value in xdmp:url-encode(xdmp:get-request-field($name))
								return fn:concat($name,'=',$value)
							),'&amp;')
						else ()
					return fn:string-join(($url,$params),'?')
			else 
				(: We already have the request parameters in the POST body; so don't duplicate them. :)
				$url
(:		let $err := fn:error()		:)
		return $url
